package com.wwj.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.common.constant.MessageConstant;
import com.wwj.common.constant.StatusConstant;
import com.wwj.common.result.PageResult;
import com.wwj.mapper.CheckMapper;
import com.wwj.mapper.SetmealCheckMapper;
import com.wwj.pojo.dto.CheckDTO;
import com.wwj.pojo.dto.CheckPageQueryDTO;
import com.wwj.pojo.entity.Check;
import com.wwj.pojo.entity.Employee;
import com.wwj.service.CheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class CheckServiceImpl implements CheckService {

    @Resource
    private CheckMapper checkMapper;

    @Resource
    private SetmealCheckMapper setmealCheckMapper;
    //新增体检项目
    @Override
    public void save(CheckDTO checkDTO) {
        Check check=new Check();
        BeanUtils.copyProperties(checkDTO,check);
        check.setStatus(StatusConstant.DISABLE);
        checkMapper.insertCheck(check);
    }

    //删除体检项目
    @Override
    public void deleteCheck(Long id) {

        Check check=checkMapper.selectById(id);
        if(check.getStatus() ==StatusConstant.ENABLE){
            throw new RuntimeException(MessageConstant.STATUS_1);
        }

        checkMapper.deleteById(id);
    }

    //编辑体检项目
    @Override
    public void updateEmployee(CheckDTO checkDTO) {
        Check check=new Check();
        BeanUtils.copyProperties(checkDTO,check);
        checkMapper.update(check);
    }

    //体检项目分页查询
    @Override
    public PageResult pageQuery(CheckPageQueryDTO checkPageQueryDTO) {
        PageHelper.startPage(checkPageQueryDTO.getPage(),checkPageQueryDTO.getPageSize());
        Page<Check> page=checkMapper.pageQuery(checkPageQueryDTO);
        long total = page.getTotal();
        List<Check> result = page.getResult();
        return new PageResult(total, result);
    }

    //启用,禁用体检项目
    @Override
    public void updateByIdAndStatus(Integer status, Long id) {
        //如果是禁用操作
        //查询当前体检项目是否关联了套餐，如果关联了就抛出业务异常
        if(status==StatusConstant.DISABLE){
            Integer count = setmealCheckMapper.countByCheckId(id);
            if(count > 0){
                //当前体检项目下关联套餐，不能禁用
                throw new RuntimeException(MessageConstant.CHECK_BE_RELATED_BY_SETMEAL);
            }
        }

        Check check=Check.builder()
                .status(status)
                .id(id)
                .build();
        log.info("check{}",check);
        checkMapper.update(check);
    }

    //查询启用检查项
    @Override
    public List<Check> list() {
        return checkMapper.list();
    }


}
